<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" media="screen" href="/css/bootstrap.min.css">
    <link rel="stylesheet" type="text/css" media="screen" href="/css/dataTables.bootstrap.min.css">
    <link rel="stylesheet" type="text/css" media="screen" href="/layui/css/layui.css">
    <link rel="stylesheet" href="/css/treetable/jquery.treetable.css"/>
    <link rel="stylesheet" href="/css/treetable/jquery.treetable.theme.default.css"/>
    <link rel="stylesheet" type="text/css" href="/css/bootstrap-select.min.css">
    <link rel="stylesheet" type="text/css" href="/at-js/css/jquery.atwho.css">
    <script src="/js/libs/jquery-2.1.1.min.js"></script>
    <script src="/js/bootstrap/bootstrap.min.js"></script>
    <script src="/js/bootstrap/bootstrap-select.min.js"></script>
    <script src="/js/jq.js"></script>
    <script src="/js/plugin/bootstrapvalidator/bootstrapValidator.min.js"></script>
    <script src="/js/common.js"></script>
    <script src="/layui/layui.js"></script>
    <script src="/js/dict.js"></script>
    <script src="/js/libs/jquery.ztree.all-3.5.min.js"></script>
    <script src="/js/my/ztree-menu.js"></script>
    <script src="/js/my/permission.js"></script>
    <script src="/js/plugin/datatables/jquery.dataTables.min.js"></script>
    <script src="/js/plugin/datatables/dataTables.bootstrap.min.js"></script>
    <script src="/js/libs/jquery.treetable.js"></script>
    <script src="/js/plugin/jquery-caret/jquery.caret.js"></script>
    <script src="/at-js/js/jquery.atwho.js"></script>
    <style>
        .layui-icon-star:hover, .layui-icon-star-fill:hover {
            cursor: pointer;
            transform: scale(1.2);
            -webkit-transform: scale(1.2);
        }
    </style>
</head>
<body>
<div style="width:99%; padding: 10px; background-color: #F2F2F2;">
    <div class="layui-row layui-col-space5">
        <div id="leftPanel" class="pagePanel layui-col-md7">
            <div class="layui-card">
                <div class="layui-card-header">
                    <table style="width: 100%">
                        <tr>
                            <td>任务列表</td>
                            <td align="right">
                                <button class="layui-btn layui-btn-sm" onclick="add()">
                                    <i class="layui-icon">&#xe608;</i> 添加
                                </button>
                            </td>
                        </tr>
                    </table>
                </div>
                <!--<div class="layui-card-body" align="left">-->
                <!--<table style="width: 100%">-->
                <!--&lt;!&ndash;<tr>&ndash;&gt;-->
                <!--&lt;!&ndash;<td>&ndash;&gt;-->
                <!--&lt;!&ndash;<form class="form-inline" onsubmit="return false">&ndash;&gt;-->
                <!--&lt;!&ndash;<div class="form-group">&ndash;&gt;-->
                <!--&lt;!&ndash;<label>成员:</label>&ndash;&gt;-->
                <!--&lt;!&ndash;<input class='form-control' type='hidden' name='participantId'&ndash;&gt;-->
                <!--&lt;!&ndash;id='participantId'>&ndash;&gt;-->
                <!--&lt;!&ndash;<input class='form-control' placeholder='成员' type='text'&ndash;&gt;-->
                <!--&lt;!&ndash;name='participantName' id='participantName'&ndash;&gt;-->
                <!--&lt;!&ndash;data-bv-notempty='true' readonly>&ndash;&gt;-->
                <!--&lt;!&ndash;<a href="#" class="layui-btn layui-btn-sm"&ndash;&gt;-->
                <!--&lt;!&ndash;onclick="showTableAndFlushFields( 'user', 'user', '用户', false, false, 'participantId:id', 'participantName:nickname')">&ndash;&gt;-->
                <!--&lt;!&ndash;<i class="layui-icon">&#xe615;</i>&ndash;&gt;-->
                <!--&lt;!&ndash;</a>&ndash;&gt;-->
                <!--&lt;!&ndash;<label>任务状态：</label>&ndash;&gt;-->
                <!--&lt;!&ndash;<select class="form-control input-sm col-md-1 selectpicker show-tick"&ndash;&gt;-->
                <!--&lt;!&ndash;name="status"&ndash;&gt;-->
                <!--&lt;!&ndash;id="status"&ndash;&gt;-->
                <!--&lt;!&ndash;title="任务状态" data-live-search="true">&ndash;&gt;-->
                <!--&lt;!&ndash;</select>&ndash;&gt;-->
                <!--&lt;!&ndash;<button id="searchBt" class="layui-btn layui-btn-sm"><i class="layui-icon">&#xe615;</i>搜索&ndash;&gt;-->
                <!--&lt;!&ndash;</button>&ndash;&gt;-->
                <!--&lt;!&ndash;</div>&ndash;&gt;-->
                <!--&lt;!&ndash;</form>&ndash;&gt;-->
                <!--&lt;!&ndash;</td>&ndash;&gt;-->
                <!--&lt;!&ndash;</tr>&ndash;&gt;-->

                <!--</table>-->
                <!--</div>-->
                <div class="layui-card-body">
                    <div class="widget-body no-padding">
                        <table id="dt-table" class="table table-striped table-bordered table-hover" style="width:100%">
                            <thead>
                            <tr>
                                <th>是否置顶</th>
                                <th>ID</th>
                                <th>任务名称</th>
                                <th>执行者</th>
                                <th>任务描述</th>
                                <th>截止日期</th>
                                <th>状态</th>
                            </tr>
                            </thead>
                            <tbody>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <div id="rightPanel" class="pagePanel layui-col-md5">
            <div class="layui-card">
                <div class="layui-card-header">
                    <div class="layui-progress" lay-filter="progress">
                        <div id="progressBar" class="layui-progress-bar" lay-percent="50%"></div>
                    </div>
                    <table style="width: 100%">
                        <tr>
                            <td align="left">
                                <h3 id="idAndName"></h3>
                            </td>
                            <td align="right">
                                <button class="layui-btn layui-btn-xs" onclick="copyTask()">
                                    <i class="layui-icon">&#xe608;</i> 复制
                                </button>
                            </td>
                        </tr>
                    </table>
                </div>
                <div class="layui-card-body" style="overflow-y:auto; height:60%">
                    <div style="width: 97%">
                        <form class="form-horizontal" onsubmit="return false" id="form">
                            <input type="hidden" id="id" name="id">
                            <div class='form-group'>
                                <label class='col-md-3 control-label'>优先级：</label>
                                <div class='col-md-8'>
                                    <div class="btn-group">
                                        <button type="button" class="btn btn-primary dropdown-toggle btn-sm"
                                                data-toggle="dropdown">
                                            <span id="grade"></span>
                                            <span class="caret"></span>
                                        </button>
                                        <ul id="gradeDropdown" class="dropdown-menu" role="menu">
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            <div class='form-group'>
                                <label class='col-md-3 control-label'>任务状态：</label>
                                <div class='col-md-8'>
                                    <div class="btn-group">
                                        <button type="button" class="btn btn-primary dropdown-toggle btn-sm"
                                                data-toggle="dropdown">
                                            <span id="status"></span>
                                            <span class="caret"></span>
                                        </button>
                                        <ul id="statusDropdown" class="dropdown-menu" role="menu">
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            <!--<div class='form-group'>-->
                            <!--<label class='col-md-3 control-label'>项目负责人：</label>-->
                            <!--<div class='col-md-8'>-->
                            <!--<input class='form-control' type='hidden' name='executorId' id='executorId'>-->
                            <!--<input style="width: 90%;float: left;" class='form-control' placeholder='负责人'-->
                            <!--type='text'-->
                            <!--name='executorName' id='executorName'-->
                            <!--readonly>-->
                            <!--<button style="width: 10%;float: right; height: 32px; line-height: 32px;"-->
                            <!--class="layui-btn layui-btn-sm"-->
                            <!--onclick="showTableExecutor('user', 'user', '用户', false, false, 'executorId:id', 'executorName:nickname');">-->
                            <!--<i class="layui-icon">&#xe615;</i>-->
                            <!--</button>-->
                            <!--</div>-->
                            <!--</div>-->
                            <div class='form-group'>
                                <label class='col-md-3 control-label'>执行者：</label>
                                <div class='col-md-8'>
                                    <input class='form-control' type='hidden' name='participantId' id='participantId'>
                                    <input style="width: 90%;float: left;" class='form-control' placeholder='执行者'
                                           type='text'
                                           name='participantName' id='participantName'
                                           readonly>
                                    <button style="width: 10%;float: right; height: 32px; line-height: 32px;"
                                            class="layui-btn layui-btn-sm"
                                            onclick="projectList()">
                                        <i class="layui-icon">&#xe615;</i>
                                    </button>
                                </div>
                            </div>

                            <div class='form-group'>
                                <label class='col-md-3 control-label'>登记工时：</label>
                                <div class='col-md-8'>
                                    <input style="width: 90%;float: left;" class="form-control" placeholder="登记工时"
                                           name="actualTotalWorkingHours"
                                           id="actualTotalWorkingHours"
                                           data-bv-notempty='true' data-bv-notempty-message='登记工时 不能为空' readonly>
                                    <button style="width: 10%;float: right; height: 32px; line-height: 32px;"
                                            class='layui-btn layui-btn-sm' title='修改登记工时'
                                            onclick='updateActualTotalWorkingHours()'><i class='layui-icon'>&#xe608;</i>
                                    </button>
                                </div>
                            </div>
                            <div class='form-group'>
                                <label class='col-md-3 control-label'>预计工时：</label>
                                <div class='col-md-8'>
                                    <input style="width: 90%;float: left;" class="form-control" placeholder="预计工时"
                                           name="estimateWorkingHours"
                                           id="estimateWorkingHours"
                                           data-bv-notempty='true' data-bv-notempty-message='预计工时 不能为空' readonly>
                                    <button style="width: 10%;float: right; height: 32px; line-height: 32px;"
                                            class='layui-btn layui-btn-sm' title='修改预计工时'
                                            onclick='updateEstimateWorkingHours()'><i class='layui-icon'>&#xe608;</i>
                                    </button>
                                </div>
                            </div>
                            <div class='form-group'>
                                <label class='col-md-3 control-label'>关联任务：</label>
                                <div class="layui-upload col-md-8">
                                    <input type="hidden" value="" id="conjunctionTaskId" name="conjunctionTaskId">
                                    <input type="hidden" value="" id="conjunctionTaskName" name="conjunctionTaskName">
                                    <button type="button" class="layui-btn layui-btn-sm" onclick="conjunctionTask()">
                                        关联任务
                                    </button>
                                    <div class="layui-upload-list">
                                        <ul id="selectedItems"></ul>
                                    </div>
                                </div>
                            </div>

                            <div class='form-group'>
                                <label class='col-md-3 control-label'>附件：</label>
                                <div class="layui-upload col-md-8">
                                    <button type="button" class="layui-btn layui-btn-danger layui-btn-sm"
                                            id="selectScreenshotPath">
                                        选择多文件
                                    </button>
                                    <input type="hidden" value="" id="screenshotPath" name="screenshotPath">
                                    <button type="button" class="layui-btn layui-btn-sm" id="uploadScreenshotPath">
                                        开始上传
                                    </button>
                                    <div class="layui-upload-list">
                                        <table class="layui-table " style="table-layout:fixed;">
                                            <thead>
                                            <tr>
                                                <th>文件名</th>
                                                <th>大小</th>
                                                <th>状态</th>
                                                <th>操作</th>
                                            </tr>
                                            </thead>
                                            <tbody id="screenshotPathList"></tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            <div class='form-group'>
                                <label class='col-md-3 control-label'>任务描述：</label>
                                <div class='col-md-8'>
                                    <!--<textarea class="form-control" placeholder="任务描述" name="description"-->
                                    <!--id="description"></textarea>-->
                                    <div class="panel panel-default" name="description"
                                         id="description" contenteditable="true"
                                         style="width: 100%; min-height: 100px;"></div>
                                </div>
                            </div>
                            <div class='form-group'>
                                <label class='col-md-3 control-label'>截止日期：</label>
                                <div class='col-md-8'>
                                    <input class='form-control' placeholder='截止日期' type='text' name='deadline'
                                           id='deadline'
                                           data-bv-notempty='true' data-bv-notempty-message='截止日期 不能为空'>
                                </div>
                            </div>
                            <div class="form-actions">
                                <div class="row" align="center">
                                    <div class="col-md-11">
                                        <button class="btn btn-primary" type="submit" onclick="save()">
                                            <i class="fa fa-save"></i> 保存
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
                <div style="padding: 0 15px;">
                    <table style="width: 100%">
                        <tr>
                            <td>动态</td>
                            <td align="right">
                                <button class="layui-btn layui-btn-sm" onclick="addMatters()" title="添加评论">
                                    <i class="layui-icon">&#xe608;</i>
                                </button>
                            </td>
                        </tr>
                    </table>
                </div>
                <div class="row" style="overflow-y:auto; width: 97%; height:25%; margin: 20px 0 0 20px;">
                    <ul id="matters" class="layui-timeline"></ul>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

<script type="text/javascript">
    layui.use(['layer', 'laydate', 'upload', 'element'], function () {
        var layer = layui.layer;
        var laydate = layui.laydate;
        var upload = layui.upload;
        var element = layui.element;

        laydate.render({
            elem: '#deadline',
            done: function (value, date, endDate) {
                // console.log(value); //得到日期生成的值，如：2017-08-18
                // console.log(date); //得到日期时间对象：{year: 2017, month: 8, date: 18, hours: 0, minutes: 0, seconds: 0}
                // console.log(endDate); //得结束的日期时间对象，开启范围选择（range: true）才会返回。对象成员同上。
                if ($("#form").data('bootstrapValidator')) {
                    $("#form").data('bootstrapValidator').resetForm();
                }
                if (value) {
                    updateField('/task/updateDeadline', 'deadline:' + value);
                }
            }
        });

        var screenshotPathListView = $('#screenshotPathList');
        var uploadListIns = upload.render({
            elem: '#selectScreenshotPath'
            , url: '/files'
            , accept: 'file'
            , multiple: true
            , auto: false
            , bindAction: '#uploadScreenshotPath'
            , choose: function (obj) {
                var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
                //读取本地文件
                obj.preview(function (index, file, result) {
                    var tr = $(['<tr id="upload-' + index + '">'
                        , '<td style ="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">' + file.name + '</td>'
                        , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                        , '<td>等待上传</td>'
                        , '<td>'
                        , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                        , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                        , '</td>'
                        , '</tr>'].join(''));

                    //单个重传
                    tr.find('.demo-reload').on('click', function () {
                        obj.upload(index, file);
                    });

                    //删除
                    tr.find('.demo-delete').on('click', function () {
                        delete files[index]; //删除对应的文件
                        tr.remove();
                        // 重新获得所有上传文件
                        $('#screenshotPath').val('');
                        $('.screenshotPathFile').each(function () {
                            $('#screenshotPath').val($('#screenshotPath').val() + '|' + $(this).data('id'));
                        });
                        uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    });

                    screenshotPathListView.append(tr);
                });
            }
            , done: function (res, index, upload) {
                if (res.code === 0) { //上传成功
                    var tr = screenshotPathListView.find('tr#upload-' + index)
                        , tds = tr.children();
                    tds.eq(0).html('<a target="_blank" data-id="' + res.data.id + '" class="screenshotPathFile" href="/files' + res.data.url + '">' + res.data.fileName + '</a>');
                    tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                    // tds.eq(3).html(''); //清空操作

                    // 追加文件id
                    $('#screenshotPath').val($('#screenshotPath').val() + '|' + res.data.id);
                    return delete this.files[index]; //删除文件队列已经上传成功的文件
                }
                this.error(index, upload);
            }
            , error: function (index, upload) {
                var tr = screenshotPathListView.find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
                tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            }
        });
    });

    function deleteItem(_this) {
        $(_this).parents('li').remove();
    }

    $(function () {
        $('.deleteItem').on('click', function () {
            deleteItem(this);
        });
    });


    var pers = checkPermission();

    $(function () {
        $('#form').bootstrapValidator();
        runAt();
    });

    var id = getUrlParam('id');

    function runAt() {
        var users = [];

        $.ajax({
            type: 'get',
            url: '/users/partList/' + id,
            async: false,
            success: function (json) {
                if (json.code === 0) {
                    users = json.data;
                }
            }
        });

        var at_config = {
            at: "@",
            data: users,
            searchKey: 'nickname',
            headerTpl: '<div class="atwho-header">User List<small>↑&nbsp;↓&nbsp;</small></div>',
            insertTpl: '<span data-id="${id}" name="atUsers">@${nickname}</span>',
            displayTpl: "<li>${nickname} <small>${username}</small></li>",
            limit: 5
        };

        var $inputor = $('#description').atwho(at_config);
        // $inputor.caret('pos', 47);
        // $inputor.focus().atwho('run');
    }

    var status = showDictSelect('status', 'task_status', '', '1');
    var grade = showDictSelect('grade', 'dept_level', '', '1');

    var example;
    var taskId = '';

    function add() {
        openIFrame('/pages/tms/task/addTask.html?projectId= ' + id, '添加任务')
    }

    function copyTask() {
        openIFrame('/pages/tms/task/copyTask.html?taskId= ' + taskId, '复制任务')
    }


    function conjunctionTask() {
        let path = '/pages/tms/task/taskTable.html?isAll=true&isMultiSelect=true&projectId=' + id;
        var flushFields = ['conjunctionTaskId:id', 'conjunctionTaskName:name'];
        let echo = []; //传输的数组
        let count = 0; //传输的数组长度
        let val = $('#' + flushFields[0].split(':')[0]).val().trim();
        if (val) {
            count = val.split(';').length;
        }

        for (let i = 0; i < count; i++) {
            let item = {};
            $.each(flushFields, function (j, field) {
                let formField = field.split(':')[0];
                let entityField = field.split(':')[1];
                item[entityField] = $('#' + formField).val().split(';')[i];
            });
            echo[i] = item;
        }

        path += '&echo=' + encodeURIComponent(JSON.stringify(echo));

        layer.open({
            type: 2,
            title: '任务列表',
            shadeClose: true, //是否点击阴影关闭层
            area: ['800px', '400px'],
            offset: 'auto', //rb右下角弹出
            anim: 0,
            content: [path, 'yes'], //iframe的url，no代表不显示滚动条
            fixed: true, // 是否固定
            maxmin: true,
            btn: ['确定', '清除', '取消'],
            yes: function (index, layero) {
                // let rows = layero.find("iframe")[0].contentWindow.example.rows('.success').data();
                let selectedItems = $(layero.find("iframe")[0]).contents().find('[name=selectedItem]');
                if (selectedItems.length == 0) {
                    $("#conjunctionTaskId").val('');
                    $("#conjunctionTaskName").val('');
                }
                if (flushFields) {
                    $.each(selectedItems, function (rowIndex, item) {
                        $.each(flushFields, function (fieldIndex, flushFiled) {
                            let fieldsPair = flushFiled.split(':');
                            if (rowIndex === 0) {
                                $('#' + fieldsPair[0].trim()).val($(item).data(fieldsPair[1].trim()));
                            } else {
                                $('#' + fieldsPair[0].trim()).val($('#' + fieldsPair[0].trim()).val().trim() + ';' + $(item).data(fieldsPair[1].trim()));
                            }
                        });
                    });
                    updateField('/task/updateConjunctionTask', 'conjunctionTaskId:' + $("#conjunctionTaskId").val(), 'conjunctionTaskName:' + $("#conjunctionTaskName").val());
                }
                layer.close(index);
            },

            cancel: function (index, layero) {
                if ($("#form").data('bootstrapValidator')) {
                    $("#form").data('bootstrapValidator').resetForm();
                }
            },
            btn2: function (index, layero) {
                if (flushFields) {
                    $.each(flushFields, function (index, item) {
                        $('#' + item.split(':')[0]).val('');
                    });
                }
                if ($("#form").data('bootstrapValidator')) {
                    $("#form").data('bootstrapValidator').resetForm();
                }
            }
        });
    }

    function projectList() {
        let path = '/pages/user/userTableForTms.html?isAll=true&isMultiSelect=false&projectId=' + id;
        var flushFields = ['participantId:id', 'participantName:nickname'];
        let echo = []; //传输的数组
        let count = 0; //传输的数组长度
        let val = $('#' + flushFields[0].split(':')[0]).val().trim();
        if (val) {
            count = val.split(';').length;
        }

        for (let i = 0; i < count; i++) {
            let item = {};
            $.each(flushFields, function (j, field) {
                let formField = field.split(':')[0];
                let entityField = field.split(':')[1];
                item[entityField] = $('#' + formField).val().split(';')[i];
            });
            echo[i] = item;
        }

        path += '&echo=' + encodeURIComponent(JSON.stringify(echo));

        layer.open({
            type: 2,
            title: '任务成员列表',
            shadeClose: true, //是否点击阴影关闭层
            area: ['800px', '400px'],
            offset: 'auto', //rb右下角弹出
            anim: 0,
            content: [path, 'yes'], //iframe的url，no代表不显示滚动条s
            fixed: true, // 是否固定
            maxmin: true,
            btn: ['确定', '清除', '取消'],

            yes: function (index, layero) {
                // let rows = layero.find("iframe")[0].contentWindow.example.rows('.success').data();
                let selectedItems = $(layero.find("iframe")[0]).contents().find('[name=selectedItem]');
                if (flushFields) {
                    $.each(selectedItems, function (rowIndex, item) {
                        $.each(flushFields, function (fieldIndex, flushFiled) {
                            let fieldsPair = flushFiled.split(':');
                            if (rowIndex === 0) {
                                $('#' + fieldsPair[0].trim()).val($(item).data(fieldsPair[1].trim()));
                            } else {
                                $('#' + fieldsPair[0].trim()).val($('#' + fieldsPair[0].trim()).val().trim() + ';' + $(item).data(fieldsPair[1].trim()));
                            }
                        });
                    })
                    updateField('/task/updateParticipant', 'participantId:' + $("#participantId").val());
                }
                layer.close(index);
            },
            cancel: function (index, layero) {
                if ($("#form").data('bootstrapValidator')) {
                    $("#form").data('bootstrapValidator').resetForm();
                }
            },
            btn2: function (index, layero) {
                if (flushFields) {
                    $.each(flushFields, function (index, item) {
                        $('#' + item.split(':')[0]).val('');
                    });
                }
                if ($("#form").data('bootstrapValidator')) {
                    $("#form").data('bootstrapValidator').resetForm();
                }
            }
        });
    }

    initList();

    function echoTask() {
        var flushFields = ['conjunctionTaskId:id', 'conjunctionTaskName:name'];
        let echoTask = []; //传输的数组
        let count = 0; //传输的数组长度
        let val = $('#' + flushFields[0].split(':')[0]).val().trim();
        if (val) {
            count = val.split(';').length;
        }

        for (let i = 0; i < count; i++) {
            let item = {};
            $.each(flushFields, function (j, field) {
                let formField = field.split(':')[0];
                let entityField = field.split(':')[1];
                item[entityField] = $('#' + formField).val().split(';')[i];
            });
            echoTask[i] = item;

            encodeURIComponent(JSON.stringify(echoTask))
        }
        if (echoTask) {
            if (echoTask.length !== 0) {
                $('#selectedItems').empty();
                $.each(echoTask, function (i, _data) {
                    let item = '<li><div style="border: 1px; overflow: hidden;">' +
                        '<a href="javascript:void(0)" onclick="parent._tabAdd(this)" data-url="pages/tms/task/conjunctionTask.html?id=' + _data['id'] + '" lay-id="888_' + _data['id'] + '" style="width: 80%; display: inline-block; white-space: nowrap; overflow: hidden;" name="selectedItem" ';

                    $.each(_data, function (k, v) {
                        // item += 'data-'+k+'="' + JSON.stringify(v) + '" ';
                        item += 'data-' + k + '="' + v + '" ';
                    });

                    item += '>' + _data['name'] + '&nbsp;</a></div></li>';

                    $('#selectedItems').append(item);
                });
            }
        }
    }


    function initList() {
        example =
            $('#dt-table').DataTable({
                "searching": false,
                "processing": false,
                "serverSide": true,
                "orderMulti": true,
                "language": {
                    "url": "/js/plugin/datatables/Chinese.lang"
                },
                "pageLength": 5,
                "ajax": {
                    "url": "/task/list",
                    "type": "get",
                    "data": function (d) {
                        // d.participantId = $('#participantId').val();
                        // d.status = $('#status').val();
                        d.projectId = id;
                    }
                },
                "dom": "<'dt-toolbar'r>t<'dt-toolbar-footer'<'col-sm-10 col-xs-12 hidden-xs'i><'col-xs-12 col-sm-10' p v>>",
                "columns": [
                    {"data": "isTop", "defaultContent": "", "visible": false},
                    {
                        "data": "id",
                        "defaultContent": "",
                        "render": function (data, type, row) {
                            return row['isTop'] == 1
                                ? data + '<i title="取消置顶" data-taskId="' + data + '" class="layui-icon layui-icon-star-fill" style="font-size: 14px; color: #FFB800; float: right;"></i>'
                                : data + '<i title="置顶" data-taskId="' + data + '" class="layui-icon layui-icon-star" style="font-size: 14px; color: #FFB800; float: right; display: none;"></i>'

                        }
                    },
                    {"data": "name", "defaultContent": "", "orderable": false,},
                    {"data": "participantName", "defaultContent": "", "orderable": false,},
                    {"data": "description", "defaultContent": "", "orderable": false,},
                    {
                        "data": "deadline",
                        "width": "60px",
                        "defaultContent": "",
                        "render": function (data, type, row) {
                            var diffDays = DateDiff(data, new Date().Format());
                            if (diffDays > 1 || row['status'] == 7 || row['status'] == 9) {
                                return "<span class='layui-badge layui-bg-green'>" + data + "</span>";
                            } else if (diffDays === 1) {
                                return "<span class='layui-badge layui-bg-orange'>" + data + "</span>";
                            } else {
                                return "<span class='layui-badge layui-bg-red'>" + data + "</span>";
                            }
                        }
                    },
                    {
                        "data": "status",
                        "defaultContent": "",
                        render: function (data, type, row) {
                            return getDict('task_status')[data];
                        }
                    },
                ],
                "initComplete": function (settings, json) {
                },
                "drawCallback": function () {
                    tableReload();
                },
                "order": [[1, "desc"]]

            });
    }

    function tableReload() {
        $('.layui-icon-star, .layui-icon-star-fill').on('click', function () {
            if ($(this).hasClass('layui-icon-star')) {
                $.ajax({
                    type: 'post',
                    url: '/task/updateIsTop/' + $(this).data('taskid') + '/1',
                    success: function (data) {
                        $(this).removeClass('layui-icon-star').addClass('layui-icon-star-fill');
                        example.ajax.reload();
                        layer.msg("设置置顶成功");
                    }
                });
            } else {
                $.ajax({
                    type: 'post',
                    url: '/task/updateIsTop/' + $(this).data('taskid') + '/0',
                    success: function (data) {
                        $(this).removeClass('layui-icon-star-fill').addClass('layui-icon-star');
                        example.ajax.reload();
                        layer.msg("取消置顶成功");
                    }
                });

            }
        });

        $('#dt-table').find('tbody tr[role=row]')
            .on('mouseover', function () {
                $(this).find('.layui-icon-star').show();
            })
            .on('mouseout', function () {
                $(this).find('.layui-icon-star').hide();
            })
            .on('click', function () {
                if (!$(this).hasClass('success')) {
                    example.$('tr.success').removeClass('success');
                    $(this).addClass('success');
                    taskId = $(this).find('td').eq(0).text();
                    initData(taskId);
                    initMatters(taskId);

                }
            });
        if (example.rows().data().length > 0) {
            if (!taskId) {
                $('#dt-table').find('tbody tr[role=row]').eq(0).click();
            }
        } else {
            $('#rightPanel').hide();
            $('#leftPanel').removeClass('layui-col-md7').addClass('layui-col-md12');
        }

    }

    function del(id) {
        layer.confirm('确定要删除吗？', {
            btn: ['确定', '取消']
        }, function () {
            $.ajax({
                type: 'delete',
                url: '/task/' + id,
                success: function (data) {
                    example.ajax.reload();
                    layer.msg("删除成功");
                }
            });

            layer.close(1);
        });
    }

    // $("#searchBt").click(function () {
    //     example.ajax.reload();
    // });

    //任务状态
    // TODO 根据现状态显示不同值
    function initDropdown(eleId, dictType, prev) {
        $('#statusDropdown').empty();
        let dictTypeList;
        $.ajax({
            type: 'get',
            url: '/statusFlow/list/' + dictType + '/' + prev,
            async: false,
            success: function (res) {
                if (res.code === 0) {
                    dictTypeList = res.data;
                    $.each(dictTypeList, function (index, data) {
                        let li;
                        if (data.k == prev) {
                            $('#' + eleId).text(data.val);
                        } else {
                            li = '<li><a href="javascript:void(0);" onclick="updateField(\'/task/updateStatus\', \'status:' + data.k + '\')">' + data.val + '</a></li>';
                        }
                        $('#statusDropdown').append(li);
                    })

                }
            }
        });
    }

    //优先级
    function initDropdownGrade(eleId, dictType) {
        $('#gradeDropdown').empty();
        let dictTypeList = getDict(dictType);
        $.each(dictTypeList, function (index, data) {
            let li = '<li><a href="javascript:void(0);" onclick="updateField(\'/task/updateGrade\', \'grade:' + index + '\')">' + data + '</a></li>';
            $('#gradeDropdown').append(li);
        })
    }


    // function showTableExecutor(module, entityName, entityComment, isAll, isMultiSelect, ...flushFields) {
    //     layer.open({
    //         type: 2,
    //         title: entityComment + '列表',
    //         shadeClose: true, //是否点击阴影关闭层
    //         area: ['800px', '400px'],
    //         offset: 'auto', //rb右下角弹出
    //         anim: 0,
    //         content: ['/pages/' + module + '/' + entityName + 'Table.html?isAll=' + isAll + '&isMultiSelect=' + isMultiSelect, 'yes'], //iframe的url，no代表不显示滚动条
    //         fixed: true, // 是否固定
    //         maxmin: true,
    //         btn: ['确定', '清除', '取消'],
    //         yes: function (index, layero) {
    //             let rows = layero.find("iframe")[0].contentWindow.example.rows('.success').data();
    //             if (flushFields) {
    //                 $.each(rows, function (rowIndex, row) {
    //                     $.each(flushFields, function (fieldIndex, item) {
    //                         let fieldsPair = item.split(':');
    //                         if (rowIndex === 0) {
    //                             $('#' + fieldsPair[0].trim()).val(row[fieldsPair[1].trim()]);
    //                         } else {
    //                             $('#' + fieldsPair[0].trim()).val($('#' + fieldsPair[0].trim()).val().trim() + ';' + row[fieldsPair[1].trim()]);
    //                         }
    //                     });
    //                 });
    //                 updateField('/task/updateExecutor', 'executorId:' + $("#executorId").val());
    //             }
    //
    //             if ($("#form").data('bootstrapValidator')) {
    //                 $("#form").data('bootstrapValidator').resetForm();
    //             }
    //             layer.close(index); //如果设定了yes回调，需进行手工关闭
    //         },
    //         cancel: function (index, layero) {
    //             if ($("#form").data('bootstrapValidator')) {
    //                 $("#form").data('bootstrapValidator').resetForm();
    //             }
    //         },
    //         btn2: function (index, layero) {
    //             if (flushFields) {
    //                 $.each(flushFields, function (index, item) {
    //                     $('#' + item.split(':')[0]).val('');
    //                 });
    //             }
    //             if ($("#form").data('bootstrapValidator')) {
    //                 $("#form").data('bootstrapValidator').resetForm();
    //             }
    //         }
    //     });
    // }

    function initData(id) {
        if (id) {
            $.ajax({
                type: 'get',
                url: '/task/' + id,
                async: false,
                success: function (json) {
                    if (json.code === 0) {
                        var data = json.data;
                        let currentUserId = getCurrentUserId();
                        $('#id').val(data.id);
                        $('#idAndName').text('#' + data.id + ' ' + data.name);
                        $('#projectId').val(data.projectId);
                        $('#participantId').val(data.participantId);
                        $('#participantName').val(data.participantName);
                        $('#conjunctionTaskId').val(data.conjunctionTaskId);
                        $('#conjunctionTaskName').val(data.conjunctionTaskName);
                        $('#selectedItems').empty();
                        echoTask();
                        // $('#executorId').val(data.executorId);
                        // $('#executorName').val(data.executorName);
                        initDropdown('status', 'task_status', data.status);
                        // $('#status').text(getDict('task_status')[data.status]);
                        if (data.executorId == currentUserId) {
                            if (data.status != 9) {
                                $('#statusDropdown').append('<li><a href="javascript:void(0);" onclick="updateField(\'/task/updateStatus\', \'status:' + 9 + '\')">确认关闭</a></li>');
                            } else {
                                $('#statusDropdown').append('<li><a href="javascript:void(0);" onclick="updateField(\'/task/updateStatus\', \'status:' + 4 + '\')">重启任务</a></li>');
                            }
                        }
                        initDropdownGrade('grade', 'dept_level');
                        $('#actualTotalWorkingHours').val(data.actualTotalWorkingHours);
                        $('#estimateWorkingHours').val(data.estimateWorkingHours);
                        // $('#description').val(data.description);
                        $('#description').html(data.description);
                        $('#deadline').val(data.deadline);
                        layui.use(['element'], function () {
                            var element = layui.element;
                            let progress = (data.status + 1) * 10;
                            if (progress <= 30) {
                                $('#progressBar').addClass('layui-bg-red');
                            } else if (progress <= 60) {
                                $('#progressBar').addClass('layui-bg-orange');
                            } else if (progress <= 90) {
                                $('#progressBar').addClass('layui-bg-green');
                            } else {
                                $('#progressBar').addClass('layui-bg-blue');
                            }
                            element.progress('progress', progress + '%');
                        });
                        $('#grade').text(getDict('dept_level')[data.grade]);
                        $('#screenshotPath').val(data.screenshotPath);
                        var screenshotPaths = data.screenshotPaths;
                        $('#screenshotPathList').empty();
                        if (screenshotPaths) {
                            $.each(screenshotPaths, function (index, file) {
                                var tr = $(['<tr id="upload-' + index + '">'
                                    , '<td style ="white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">'
                                    , '<a target="_blank" data-id="' + file.id + '" class="screenshotPathFile" href="/files' + file.url + '">' + file.fileName + '</a>'
                                    , '</td>'
                                    , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                                    , '<td>已上传</td>'
                                    , '<td>'
                                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                                    , '</td>'
                                    , '</tr>'].join(''));

                                //单个重传
                                tr.find('.demo-reload').on('click', function () {
                                    obj.upload(index, file);
                                });

                                //删除
                                tr.find('.demo-delete').on('click', function () {
                                    // delete files[index]; //删除对应的文件
                                    tr.remove();
                                    // 重新获得所有上传文件
                                    $('#screenshotPath').val('');
                                    $('.screenshotPathFile').each(function () {
                                        $('#screenshotPath').val($('#screenshotPath').val() + '|' + $(this).data('id'));
                                    });
                                });

                                $('#screenshotPathList').append(tr);
                            });
                        }


                        $('#form button').removeAttr('disabled');
                        if (data.executorId != currentUserId
                            && data.participantId != currentUserId
                            && data.createBy != currentUserId
                            && 1 != currentUserId) {
                            $('#form button').attr('disabled', true);
                        }
                    }
                }
            });
        }
    }

    function initMatters(_id) {
        $.ajax({
            type: 'get',
            url: '/matters/listAll/' + _id,
            success: function (res) {
                if (res.code === 0) {
                    let data = res.data;
                    $('#matters').empty();
                    $.each(data, function (index, matter) {
                        let timeline = '<li class="layui-timeline-item">';
                        timeline += '<i class="layui-icon layui-timeline-axis">&#xe63f;</i>';
                        timeline += '<div class="layui-timeline-content layui-text">';
                        timeline += '<h4 class="layui-timeline-title">';
                        timeline += matter['createTime'] + ' ' + matter['createByName'];
                        timeline += '</h4><p>';
                        timeline += matter['msg'];
                        timeline += '</p></div></li>';
                        $('#matters').append(timeline);
                    })
                }
            }
        });
    }

    function save() {
        $('#form').bootstrapValidator();
        var bootstrapValidator = $("#form").data('bootstrapValidator');
        bootstrapValidator.validate();
        if (!bootstrapValidator.isValid()) {
            return;
        }

        var formdata = $("#form").serializeObject();
        formdata.description = $('#description').html();
        formdata.atUsers = [];

        $.each($('#form').find('[name=atUsers]'), function (index, item) {
            formdata.atUsers[index] = $(item).data("id");
        });

        $.ajax({
            type: 'put',
            url: '/task',
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(formdata),
            success: function (data) {
                layer.msg("修改成功", {shift: -1, time: 1000}, function () {
                    // location.reload();
                    if ($("#form").data('bootstrapValidator')) {
                        $("#form").data('bootstrapValidator').resetForm();
                    }
                    refreshTask();
                });
            }
        });
    }

    function updateField(url, ...kv) {
        let json = {};
        json['id'] = taskId;
        if (kv) {
            $.each(kv, function (index, item) {
                json[item.split(':')[0].trim()] = item.split(':')[1].trim();
            });
        }

        $.ajax({
            type: 'post',
            url: url,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(json),
            success: function (data) {
                layer.msg("修改成功", {shift: -1, time: 1000}, function () {
                    // location.reload();
                    refreshTask();
                });
            }
        });
    }


    var validatorSettings = {
        message: '验证不通过',
        fields: {
            actualTotalWorkingHours: {
                message: '登记工时验证失败',
                validators: {
                    notEmpty: {
                        message: '登记工时不能为空'
                    }, numeric: {
                        message: '登记工时只能输入数字'
                    }, greaterThan: {
                        value: 0,
                        message: '登记工时必须为正数'
                    },
                    lessThan: {
                        value: 9999,
                        message: '登记工时必须小于10000'
                    }
                }
            }
        },
        submitHandler: function (validator, form, submitButton) {
            alert("submit");
        }
    };

    var escValidatorSettings = {
        message: '验证不通过',
        fields: {
            estimateWorkingHours: {
                message: '预计工时验证失败',
                validators: {
                    notEmpty: {
                        message: '预计工时不能为空'
                    }, numeric: {
                        message: '预计工时只能输入数字'
                    }, greaterThan: {
                        value: 0,
                        message: '预计工时必须为正数'
                    },
                    lessThan: {
                        value: 9999,
                        message: '预计工时必须小于10000'
                    }
                }
            }
        },
        submitHandler: function (validator, form, submitButton) {
            alert("submit");
        }
    };

    function updateActualTotalWorkingHours() {
        layer.open({
            id: "submit",
            type: 2,
            title: '修改登记工时',
            // skin: "layui-layer-molv",   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
            shadeClose: true,
            shade: 0.3,
            maxmin: true, //开启最大化最小化按钮
            success: function (layero, index) {
                var body = layer.getChildFrame('body', index);
                var actualTotalWorkingHours = $("#actualTotalWorkingHours").val();
                body.contents().find("#actualTotalWorkingHours").val(actualTotalWorkingHours);
            },
            area: ['300px', '180px'],
            content: ['updateAct.html', 'yes'],
            btn: ["保存", "关闭"],
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index);
                body.contents().find("#form").bootstrapValidator(validatorSettings);
                body.contents().find("#form").bootstrapValidator();
                var bootstrapValidator = body.contents().find("#form").data('bootstrapValidator');
                bootstrapValidator.validate();
                if (!bootstrapValidator.isValid()) {
                    return;
                }
                var data = body.contents().find("#form").serializeObject();
                return updateField('/task/updateActualTotalWorkingHours', 'actualTotalWorkingHours:' + data.actualTotalWorkingHours);
            },
            btn2: function (index, layero) {
                layer.close(index);
            },
        });
    }

    function updateEstimateWorkingHours() {
        layer.open({
            id: "submit",
            type: 2,
            title: '修改预计工时',
            // skin: "layui-layer-molv",   //layui-layer-lan:蓝色，layui-layer-molv：墨绿色，默认灰色
            shadeClose: true,
            shade: 0.3,
            maxmin: true, //开启最大化最小化按钮
            success: function (layero, index) {
                var body = layer.getChildFrame('body', index);
                var estimateWorkingHours = $("#estimateWorkingHours").val();
                body.contents().find("#estimateWorkingHours").val(estimateWorkingHours);
            },
            area: ['300px', '180px'],
            content: ['updateEst.html', 'yes'],
            btn: ["保存", "关闭"],
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index);

                body.contents().find("#form").bootstrapValidator(escValidatorSettings);
                body.contents().find("#form").bootstrapValidator();
                var bootstrapValidator = body.contents().find("#form").data('bootstrapValidator');
                bootstrapValidator.validate();
                if (!bootstrapValidator.isValid()) {
                    return;
                }
                var data = body.contents().find("#form").serializeObject();
                return updateField('/task/updateEstimateWorkingHours', 'estimateWorkingHours:' + data.estimateWorkingHours);
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
            },
        });
    }

    function resizePanel() {
        $('.layui-card').height($(window).height() * 0.94);
    }

    function refreshTask() {
        let taskIdBefore = taskId;
        example.ajax.reload(function () {
            $('[data-taskid=' + taskIdBefore + ']').parents('tr').trigger('click');
        }, false);
    }

    // 添加评论 TODO
    function addMatters() {
        let layerWidth = 600;
        let layerHeight = 400;
        layer.open({
            type: 2,
            title: '添加评论',
            shadeClose: true,
            shade: 0.3,
            maxmin: false, //开启最大化最小化按钮
            move: false,
            offset: 'rb',
            success: function (layero, index) { // 弹出后的回调

            },
            area: [layerWidth + 'px', layerHeight + 'px'],
            content: ['addMatters.html', 'yes'],
            btn: ["保存", "关闭"],
            yes: function (index, layero) {
                let layerForm = $(layero.find("iframe")[0]).contents().find('#form');
                let mattersData = {};
                mattersData.taskId = taskId;
                mattersData.msg = layerForm.find('#msg').html();
                mattersData.atUsers = [];

                $.each(layerForm.find('[name=atUsers]'), function (index, item) {
                    mattersData.atUsers[index] = $(item).data("id");
                });

                $.ajax({
                    type: 'post',
                    url: '/matters',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify(mattersData),
                    success: function (data) {
                        layer.msg("添加评论成功", {shift: -1, time: 1000}, function () {
                            // location.reload();
                        });
                    }
                });
                refreshTask();
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
            },
        });
    }

    resizePanel();
</script>
